﻿using MCP.BL;
using MCP.Data.CF_Entities;
using MCP.Model.Auth;
using MCP.Model.Helpers;
using MCP.Model.Repositories.Interfaces;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using client = MCP.Data.Client;
using MessageHelper = MoneyCounter.Helpers.MessageHelper;

namespace MoneyCounter.Controllers
{
	public class AccountController : BaseControllerWithDatasource
	{
		private readonly MCPMembershipProvider membership = new MCPMembershipProvider();
		private MessageHelper messageHelper = new MessageHelper();

        public AccountController(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
			
        }

		[AllowAnonymous]
		public ActionResult LogIn()
		{
			client.User model = new client.User {Username = "user", Password = "user"};
			return View(model);
		}

		[AllowAnonymous]
		[HttpPost]
		public ActionResult LogIn(client.User model)
		{
			using (var db = new MCPDB())
			{
				var userCount = db.Users.Count();
			}

			var authentificationResult = membership.Validate(model.Username, model.Password, this.unitOfWork);

			if (authentificationResult.ResultType == AuthenticationResultType.Authorized)
			{
				FormsAuthentication.Initialize();
				FormsAuthentication.SetAuthCookie(model.Username, false);

				messageHelper.ClearLogInError(this);

				string role = model.Username == "admin" ? "admin" : "user";

			    var setCurrentUserResult = CurrentUserHelper.SetCurrentUser(model.Username, role, this.unitOfWork);
				if (!setCurrentUserResult.Success)
				{
					//throw new Exception("Unable to find User by its ID while setting Session CurrentUser.");
                    this.messageHelper.SetCustomAuthenticationErrorMessage(
                        this,
                        setCurrentUserResult.Messages.FirstOrDefault().Text,
                        AuthenticationResultType.Other,
                        ErrorNotificationPlace.General);
				    return this.LogIn();
				}

				if (role == "admin")
				{
					return this.RedirectToAction("AdminPanelAction", "AdminPanel");
				}
				else
				{
					return this.RedirectToAction("UserMenu", "UserMenu");
				}
			}
			else
			{
				messageHelper.SetDefaultAuthenticationErrorMessage(this, authentificationResult);
				return this.LogIn();
			}
		}

		public ActionResult LogOut()
		{
			FormsAuthentication.SignOut();
			return View();
		}

        [AllowAnonymous]
        public ActionResult About()
        {
            return this.View();
        }

        [AllowAnonymous]        
        public ActionResult NewDevInstanceInitialization()
        {
            this.unitOfWork.AccountRepository.InitializeBaseUsers();
            return this.View();
        }
	}
}
